#include "stdafx.h"

TCHAR Document::currentFileName[MAX_PATH] = TEXT("Book1");
TCHAR Document::currentFileTitle[MAX_PATH] = TEXT("Book1");
int Document::iCount = 1;
bool Document::hasFileName = false;

/*********************************
 * Create a new document
 ***/
bool Document::New()
{
	// Clear the old sheets
	delete currentSheet;
	currentSheet = new Sheet();
	// Clear the history
	objHistory.Clear();
	isModified = false;
	
	iCount++;
	// Clear the file name
	::ZeroMemory(currentFileName, MAX_PATH);
	::ZeroMemory(currentFileTitle, MAX_PATH);
	hasFileName = false;
	::wsprintf(currentFileName, TEXT("Book%d"), GetCount());
	::wsprintf(currentFileTitle, TEXT("Book%d"), GetCount());
	return true;
}

/*********************************
 * Open a document
 ***/
bool Document::Open(PTSTR FileName)
{

	// Clear the old sheets
	delete currentSheet;
	currentSheet = new Sheet();
	// Clear the history
	objHistory.Clear();
	isModified = false;

	TCHAR szExt[4] = TEXT("");
	FileDialog::GetFileExt(FileName, szExt);

	// Select a Opener
	OpenBuilder* pOpener= 0;
	if ( _tcscmp(szExt,TEXT("CSV"))==0 )
	{
		pOpener = new CSVOpener(FileName, currentSheet);
	}

	// Cannot open the specific file
	if (pOpener == 0)
	{
		return false;
	}

	// Execute OpenCommand
	OpenCommand openCommand;
	openCommand.Init(pOpener);
	if (!openCommand.Execute())
	{
		delete pOpener;
		pOpener = 0;
		return false;
	}
	UpdateFileName(FileName);
	delete pOpener;
	pOpener = 0;
	hasFileName = true;
	return true;
}

bool Document::Save()
{
	return SaveAs(currentFileName);
}

bool Document::SaveAs(PTSTR FileName)
{
	TCHAR szExt[4] = TEXT("");
	FileDialog::GetFileExt(FileName, szExt);

	// Select a Saver
	SaveBuilder* pSaver= 0;
	if ( _tcscmp(szExt,TEXT("CSV"))==0 )
	{
		pSaver = new CSVSaver(FileName, currentSheet);
	}

	// Cannot save the specific file
	if (pSaver == 0)
	{
		return false;
	}

	// Execute SpenCommand
	SaveCommand saveCommand;
	saveCommand.Init(pSaver);
	if (!saveCommand.Execute())
	{
		delete pSaver;
		pSaver = 0;
		return false;
	}
	UpdateFileName(FileName);
	delete pSaver;
	pSaver = 0;
	hasFileName = true;
	isModified = false;
	return true;
}

bool Document::Undo()
{
	if (CanUndo())
	{
		objHistory.Undo();
		isModified = true;
		return true;
	}
	return false;
}

bool Document::Redo()
{
	if (CanRedo())
	{
		objHistory.Redo();
		isModified = true;
		return true;
	}
	return false;
}

bool Document::AddCmdStep(Command* objCommand)
{
	objHistory.Record(objCommand);
	isModified = true;
	return true;
}